<template>
  <div class="tableWrap">
    <div class="flex_start contrller">
      <el-button type="primary" :icon="'CirclePlus'" @click="addUser">新增</el-button>
      <el-input
        v-model="userParams.username"
        placeholder="请输入账号"
        class="searchSty"
        @keyup.enter.native="searchList"
      >
        <template #append>
          <el-button :icon="'Search'" @click="searchList" />
        </template>
      </el-input>

      <el-button type="primary" :icon="'RefreshRight'" @click="resetList">重置</el-button>
    </div>

    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column type="index" width="50">
        <template #default="scope">
          {{ (userParams.pageNum - 1) * userParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="nickname" align="center" label="用户名" width="180" />
      <el-table-column prop="username" align="center" label="账号" width="180" />
      <!-- <el-table-column prop="roleIds" align="center" label="角色" /> -->
      <el-table-column prop="companyName" align="center" label="部门" />
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag
            class="ml-2 pointer"
            type="success"
            v-if="scope.row.status == 1"
            @click="changeStatus(scope.row.id, 0)"
            >已启用</el-tag
          >
          <!-- <span>{{ scope.row.status == 1 ? '已启用' : '已禁用' }}</span> -->
          <el-tag
            class="ml-2 pointer"
            type="danger"
            v-if="scope.row.status == 0"
            @click="changeStatus(scope.row.id, 1)"
            >已禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="action" label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="updateUserFunc(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm title="确定重置吗?" @confirm="resetPwd(scope.row.id)">
            <template #reference>
              <el-button link type="danger" size="small">密码重置</el-button>
            </template>
          </el-popconfirm>
          <!-- <el-button link type="danger" size="small" @click="resetPwd">密码重置</el-button> -->
          <!-- <el-button link type="danger" size="small">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-10"
      @current-change="changePage"
      :current-page="userParams.pageNum"
      :page-size="userParams.pageSize"
      background
      layout="prev, pager, next"
      :total="total"
      hide-on-single-page
    />

    <el-dialog
      v-model="centerDialogVisible"
      :title="isUpdate ? '更新用户' : '新增用户'"
      width="40%"
      align-center
    >
      <p class="iptwrap">
        <span><sup class="require">*</sup>用户名：</span>
        <el-input
          v-model="sizeForm.nickname"
          placeholder="请输入用户名"
          clearable
          class="iptwidth"
        />
      </p>
      <p class="iptwrap">
        <span><sup class="require">*</sup>账号：</span>
        <el-input
          v-model="sizeForm.username"
          :disabled="isUpdate ? true : false"
          placeholder="请输入账号"
          clearable
          class="iptwidth"
        />
      </p>
      <p class="iptwrap" v-if="!isUpdate">
        <span><sup class="require">*</sup>密码：</span>
        <el-input
          v-model="sizeForm.password"
          type="password"
          placeholder="密码包含 数字,英文,字符中的两种以上，长度6-20"
          show-password
          autocomplete="new-password"
          class="iptwidth"
        />
      </p>
      <!-- <p class="iptwrap">
        <span><sup class="require">*</sup>密码确认：</span>
        <el-input
          v-model="sizeForm.psw2"
          type="password"
          placeholder="请再次输入密码"
          show-password
          class="iptwidth"
        />
      </p> -->
      <p class="iptwrap">
        <span><sup class="require">*</sup>账号类型：</span>
        <el-select v-model="sizeForm.type" placeholder="请选择账号类型" class="iptwidth">
          <el-option
            v-for="item in accountType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </p>
      <p class="iptwrap">
        <span><sup class="require">*</sup>部门：</span>
        <!-- <el-select
          v-model="sizeForm.group"
          placeholder="请选择状态"
          class="iptwidth"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <!-- <el-tree-select
          v-model="value"
          :data="orgList"
          check-strictly
					@change="treeSlc"
          :render-after-expand="false"
        /> -->
        <el-cascader
          v-model="historyData"
          :props="cascader"
          :options="orgList"
          @change="(e) => handleChange(e)"
          placeholder="请选择部门"
          style="width: 60%"
        />
      </p>
      <p class="iptwrap">
        <span>手机号：</span>
        <el-input
          v-model="sizeForm.mobile"
          type="tel"
          placeholder="请输入手机号"
          maxlength="11"
          class="iptwidth"
        />
      </p>
      <p class="iptwrap">
        <span><sup class="require">*</sup>角色：</span>
        <el-select v-model="sizeForm.roleIds" multiple placeholder="请选择角色" class="iptwidth">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </p>
      <p class="iptwrap">
        <span><sup class="require">*</sup>状态：</span>
        <el-select v-model="sizeForm.status" placeholder="请选择状态" class="iptwidth">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </p>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreate" v-if="!isUpdate"> 确定 </el-button>
          <el-button type="primary" @click="confirmUpdate" v-if="isUpdate"> 更新 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { defineComponent, reactive, toRefs, ref, onMounted } from 'vue';

import {
  findUserList,
  createUser,
  updateUser,
  updateUserStatus,
  resetPassword,
  getUserInfoById,
  checkUsername,
} from '@/api/system/user/index.ts';
import { queryTreeList } from '@/api/system/menu/index.ts';
import { getAllRole } from '@/api/system/role/index.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PUBLIC_KEY } from '@/utils/common';
import { JSEncrypt } from '@/utils/jsencrypt';

export default defineComponent({
  setup() {
    const state = reactive({
      centerDialogVisible: false,
      isUpdate: false,
      cascader: {
        value: 'id',
        label: 'label',
        // multiple: true,
        // checkStrictly: true,
      },
      options: [
        {
          value: 1,
          label: '启用',
        },
        {
          value: 0,
          label: '禁用',
        },
      ],
      accountType: [
        {
          value: '1',
          label: '后台管理员',
        },
        {
          value: '0',
          label: '普通用户',
        },
      ],
      userParams: {
        username: '',
        nickname: '',
        pageSize: 20,
        pageNum: 1,
      },
      total: 1,
      sizeForm: {
        username: '',
        nickname: '',
        password: '',
        mobile: '',
        companyId: '',
        roleIds: [],
        status: 1,
        type: '0',
      },
      historyData: [],
      label: '',
      tableData: [],
      roleList: [],
      orgList: [],
    });
    //递归增加value属性 级联选择需要value字段
    const loopData = (data = []) => {
      data.map((item) => {
        if (item.children?.length) {
          loopData(item.children);
          item.value = item.label;
        } else {
          item.value = item.label;
          return item;
        }
      });
      return data;
    };

    //根据自节点查找所有父节点
    const loopParentIds = (nodeId) => {
      let dataSource = state.orgList;
      const parentIds = []; // 用于存储所有父节点ID的数组

      // 定义一个递归函数，用于遍历整棵树并查找子节点的所有父节点
      function traverse(node, nodeId) {
        if (node.id === nodeId) {
          // 如果当前节点的ID等于子节点的ID，则表示已经找到了子节点，可以开始向上查找父节点
          return true; // 返回true表示已经找到了子节点
        }

        if (node.children) {
          // 如果当前节点有子节点，则继续遍历子节点
          for (const childNode of node.children) {
            if (traverse(childNode, nodeId)) {
              // 如果在子节点中找到了子节点的父节点，则将当前节点的ID添加到父节点ID数组中，并返回true表示已经找到了子节点
              parentIds.unshift(node.id);
              return true;
            }
          }
        }

        return false; // 如果当前节点不是子节点的父节点，则返回false
      }

      // 从根节点开始遍历整棵树，并调用递归函数查找子节点的所有父节点
      for (const node of dataSource) {
        if (traverse(node, nodeId)) {
          // 如果在当前节点的子树中找到了子节点的父节点，则直接退出循环
          break;
        }
      }

      return parentIds; // 返回所有父节点ID的数组
    };
    const roleAndOrgList = () => {
      queryTreeList({}).then((res) => {
        // res.map(item=>{
        // 	item.value = item.id
        // 	return item
        // })
        // let ddd = loopData(res);
        // console.log('ddd', ddd);
        state.orgList = loopData(res);
      });
      getAllRole({}).then((resR) => {
        state.roleList = resR;
      });
    };
    const treeSlc = (e) => {
      console.log('e', e);
    };
    const handleChange = (value) => {
      console.log(value);
      state.sizeForm.companyId = value[value.length - 1];
    };
    const addUser = () => {
      state.centerDialogVisible = true;
      state.isUpdate = false;
      state.sizeForm={
        username: '',
        nickname: '',
        password: '',
        mobile: '',
        companyId: '',
        roleIds: [],
        status: 1,
        type: '0',
      }
    };
    const confirmCreate = () => {
      // console.log("params",state.sizeForm);
      if (!state.sizeForm.nickname) {
        ElMessage({
          message: '请输入用户名',
          type: 'warning',
        });
        return;
      }
      if (!state.sizeForm.username) {
        ElMessage({
          message: '请输入账号',
          type: 'warning',
        });
        return;
      }
      if (!state.sizeForm.password) {
        ElMessage({
          message: '请输入密码',
          type: 'warning',
        });
        return;
      }
      if (!state.sizeForm.companyId) {
        ElMessage({
          message: '请选择部门',
          type: 'warning',
        });
        return;
      }
      if (!state.sizeForm.roleIds.length) {
        ElMessage({
          message: '请选择角色',
          type: 'warning',
        });
        return;
      }
      if (state.sizeForm.status != 0 && state.sizeForm.status != 1) {
        ElMessage({
          message: '请选择状态',
          type: 'warning',
        });
        return;
      }
      
      checkUsername({ username: state.sizeForm.username }).then((rname) => {
        // console.log("rname",rname);
        if (!rname) {
          ElMessage({
            message: '当前账号已注册！',
            type: 'warning',
          });
          return;
        }
      });
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey(PUBLIC_KEY);
      // state.sizeForm.username = encrypt.encrypt(state.sizeForm.username);
      // state.sizeForm.password = encrypt.encrypt(state.sizeForm.password);
      createUser({
        ...state.sizeForm,
        username:encrypt.encrypt(state.sizeForm.username),
        password:encrypt.encrypt(state.sizeForm.password),
      }).then((createRes) => {
        ElMessage({
          message: '操作成功',
          type: 'success',
        });
        state.sizeForm = {
          username: '',
          nickname: '',
          password: '',
          // psw2:'',
          mobile: '',
          // group:'',
          roleIds: [],
          status: '',
          type: '1',
        };
        state.centerDialogVisible = false;
        queryUserList();
      });
    };
    const userInfoSet = (id) => {
      getUserInfoById(id).then((res) => {
        // console.log('res,', res);
        // const { pid, sort, id, name, pname } = res;
        if (state.isUpdate) {
          state.historyData = [];
          let companyIds = loopParentIds(res.companyId);
          state.sizeForm = {
            username: res.username,
            nickname: res.nickname,
            // password: '',
            mobile: res.mobile,
            companyId: res.companyId,
            roleIds: res.roleIds,
            status: res.status,
            id: res.id,
            type: res.type,
          };
          state.historyData = [...companyIds, res.companyId];
          // console.log('companyIds', [...companyIds, res.companyId]);
        } else {
        }
      });
    };
    const confirmUpdate = () => {
      if (!state.sizeForm.nickname) {
        ElMessage({
          message: '请输入用户名',
          type: 'warning',
        });
        return;
      }
      // if (!state.sizeForm.password) {
      //   ElMessage({
      //     message: '请输入密码',
      //     type: 'warning',
      //   });
      //   return;
      // }
      if (!state.sizeForm.companyId) {
        ElMessage({
          message: '请选择部门',
          type: 'warning',
        });
        return;
      }
      if (!state.sizeForm.roleIds.length) {
        ElMessage({
          message: '请选择角色',
          type: 'warning',
        });
        return;
      }
      updateUser(state.sizeForm).then((createRes) => {
        ElMessage({
          message: '操作成功',
          type: 'success',
        });
        state.sizeForm = {
          username: '',
          nickname: '',
          password: '',
          // psw2:'',
          mobile: '',
          // group:'',
          roleIds: [],
          status: '',
          type: '1',
        };
        state.centerDialogVisible = false;
        queryUserList();
      });
    };
    const updateUserFunc = (index, item) => {
      // console.log('item-data', item);
      if (item) {
        state.isUpdate = true;
        state.sizeForm = item;
        // state.sizeForm.status = item.status == 1 ? '启用' :'禁用'
        state.centerDialogVisible = true;
        userInfoSet(item.id);
      }
    };
    const queryUserList = () => {
      findUserList(state.userParams).then((res) => {
        // console.log("res===>",res);
        const { total, rows } = res;
        state.total = total;
        state.tableData = rows;
      });
    };
    const changeStatus = (userId, status) => {
      updateUserStatus({ userId, status: String(status) }).then((res) => {
        ElMessage({
          message: '操作成功',
          type: 'success',
        });
        queryUserList();
      });
    };
    const searchList = () => {
      queryUserList();
    };

    const resetList = () => {
      state.userParams = {
        username: '',
        nickname: '',
        pageSize: 30,
        pageNum: 1,
      };
      queryUserList();
    };
    const resetPwd = (userId) => {
      resetPassword({ userId }).then((resR) => {
        ElMessage({
          message: '新密码：12345678',
          type: 'success',
          duration: 5000,
        });
      });
    };
    const changePage = (val) => {
      state.userParams.pageNum = val;
      queryUserList();
    };
    onMounted(() => {
      queryUserList();
      roleAndOrgList();
    });

    return {
      ...toRefs(state),
      confirmCreate,
      queryUserList,
      updateUserFunc,
      confirmUpdate,
      changeStatus,
      searchList,
      resetList,
      resetPwd,
      treeSlc,
      changePage,
      addUser,
      handleChange,
      userInfoSet,
    };
  },
});
</script>
<style lang="less" scoped>
.tableWrap {
  :deep(.el-table) {
    background-color: transparent !important;
    font-size: 0.7vw;
    thead {
      color: #333 !important;
    }
    tr {
      background-color: transparent !important;
      color: #333;
    }
    tr:hover > td {
      background: rgba(255, 255, 255, 0.1) !important;
    }
    th {
      background-color: transparent !important;
      border-bottom: none !important;
      color: #333;
    }
    &::before {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0px;
    }
  }
  :deep(.el-table--enable-row-transition .el-popper .is-light) {
    background-color: rgba(255, 255, 255, 1) !important;
    border: 1px solid #fff !important;
  }
  :deep(.el-input__inner) {
    color: #333 !important;
  }
  .iptwrap {
    margin-bottom: 15px;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      .require {
        color: #f5222d;
      }
    }
  }
  .contrller {
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
  }
  .searchSty {
    width: 300px;
    margin: 0 10px;
  }
  .iptwidth {
    width: 60%;
  }
  .pointer {
    cursor: pointer;
  }
}
</style>
